package com.xjcs.saplingplan.adapter

import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.xjcs.saplingplan.const.setSingleClick
import com.xjcs.saplingplan.const.toColor
import com.xjcs.saplingplan.databinding.ItemMemoToolsBinding
import com.xjcs.saplingplan.model.bean.memo.MemoToolsBean

class MemoToolsAdapter(
    private val context: Context,
    private val list: MutableList<MemoToolsBean>,
    private val callback: (Int) -> Unit
): RecyclerView.Adapter<MemoToolsAdapter.ItemMemoToolsViewHolder>() {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemMemoToolsViewHolder {
        val binding = ItemMemoToolsBinding.inflate(LayoutInflater.from(context), parent, false)
        return ItemMemoToolsViewHolder(binding)
    }

    override fun getItemCount(): Int {
        return list.size
    }

    override fun onBindViewHolder(holder: ItemMemoToolsViewHolder, position: Int) {
        val item = list.getOrNull(position)
        holder.binding.root.setSingleClick {
            callback.invoke(position)
        }
        holder.bind(context, item)
    }

    class ItemMemoToolsViewHolder(val binding: ItemMemoToolsBinding) : RecyclerView.ViewHolder(binding.root){

        private val color34C759 = "#34C759".toColor()

        fun bind(context: Context, item: MemoToolsBean?) {
            item?.let {
                Glide.with(context).load(item.res).into(binding.ivImg)
                if(item.selected){
                    binding.ivImg.setColorFilter(color34C759)
                }else{
                    binding.ivImg.clearColorFilter()
                }
            }
        }
    }
}